/**
 * Created by CXinZhi on 2016/10/25.
 */

import compare.ChangeExcelName;
import compare.ExcelDirectory;
import compare.ExcelFile;
import compare.util.FileUtils;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main extends Application {

	public static void main(String[] args) {
		launch(args);
	}

	List<ChangeExcelName> listCom;

	String strDate = "";
	String rootPath = "";
	String newRootPath = "";
	String pName = "";
	String cName = "";
	Integer fileCount = 0;
	Integer direCount = 0;
	StringBuilder megDetail = null;

	@Override
	public void start(Stage primaryStage) throws IOException {
		try {
			Class<?> macFontFinderClass = Class.forName("com.sun.t2k.MacFontFinder");
			Field psNameToPathMap = macFontFinderClass.getDeclaredField("psNameToPathMap");
			psNameToPathMap.setAccessible(true);
			psNameToPathMap.set(null, new HashMap<String, String>());
		} catch (Exception e) {
			// ignore
		}

		Parent root = FXMLLoader.load(getClass().getResource("compare.fxml"));
		primaryStage.setTitle("CN 1.0 for xls");
		primaryStage.setScene(new Scene(root, 1024, 768));

		final Button btnCom = (Button) root.lookup("#btnStartCom");

		final TextField txtRootPath = (TextField) root.lookup("#txtRootPath");
		final TextField txtPastName = (TextField) root.lookup("#txtPastName");
		final TextField txtChangeName = (TextField) root.lookup("#txtChangeName");

		final Label lblResult = (Label) root.lookup("#lblResult");
		final TextArea txtDetail = (TextArea) root.lookup("#txtDetail");

		btnCom.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				megDetail = new StringBuilder();
				Date curDate = new Date();
				DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

				strDate = "[新" + df.format(curDate) + "]";
				rootPath = txtRootPath.getText();
				pName = txtPastName.getText();
				cName = txtChangeName.getText();

				listCom = new ArrayList<ChangeExcelName>();

				lblResult.setText("");
				txtDetail.setText("");

				if (!isExistDir(rootPath)) {
					txtDetail.setText("                路径不存在，请重新输入！");
					return;
				}

				try {
					doChange(rootPath, txtPastName.getText(), txtChangeName.getText());
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

				megDetail.append("         本次替换结束\n\n\n");

				Collections.sort(listCom, new Comparator<ChangeExcelName>() {
					public int compare(ChangeExcelName arg0, ChangeExcelName arg1) {
						return arg0.getChange().compareTo(arg1.getChange());
					}
				});

				for (ChangeExcelName ce : listCom) {
					if (ce.isChange())
						megDetail.append(ce.getMatchMeg() + "\n");

					if (ce.isChange())
						fileCount++;

				}

				lblResult.setText(String.format("本次修改共 %s 文件，修改文件夹  %s 个 ", fileCount, direCount));

				txtDetail.setText(megDetail.toString());
			}
		});

		primaryStage.show();
	}


	/**
	 * 通过目录 修改科目名称
	 *
	 * @param path
	 * @param pastName
	 * @param changeName
	 */
	public void doChange(String path, String pastName, String changeName) throws Exception {

		int rootLevel = 0;

		ExcelDirectory rootDirec = new ExcelDirectory(rootLevel, "根目录", path, "", rootPath);

		newRootPath = rootPath + strDate;

		FileUtils.makeDirs(newRootPath);

		// 加载 根目录1 下所有的 excle
		loadFile(rootDirec, path);

		// 开始替换
		startChange(rootDirec, pastName, changeName);

	}

	/**
	 * 开始进行替换
	 */
	public void startChange(ExcelDirectory directory, String pName, String cName) throws IOException {

		System.out.println(String.format("\n当前路径级别[%s],替换文件夹路径[%s] ,文件数[%s]", directory.getLevel(),
				directory.getDirectoryPath(), directory.getFileList().size()));

		for (ExcelFile file : directory.getFileList()) {
			changeName(file, pName, cName);
		}

		if (directory.getChildDirectorys().size() < 0)
			return;

		for (ExcelDirectory dir : directory.getChildDirectorys()) {
			startChange(dir, pName, cName);
		}
	}

	/**
	 * 开始替换文件内容
	 *
	 * @param changeFile
	 * @param pName
	 * @param cName
	 */
	private void changeName(ExcelFile changeFile, String pName, String cName) throws IOException {
		ChangeExcelName changeName = new ChangeExcelName(changeFile.getFilePath(), changeFile.fielName, pName, cName,
				changeFile.newPath.replaceAll(pName, cName));

		changeName.doChange();

		listCom.add(changeName);
	}


	/**
	 * 加载目录下所有文件 和 目录信息
	 *
	 * @param directory
	 */
	public void loadFile(ExcelDirectory directory, String rootPath) throws Exception {

		try {
			Integer level = directory.getLevel() + 1;

			File root = new File(directory.getDirectoryPath());

			File[] list = root.listFiles();

			List<ExcelFile> files = new ArrayList<ExcelFile>();

			if (list == null) return;

			for (File f : list) {
				if (f.isDirectory()) {

					// 下一级别对比文件夹
					ExcelDirectory childDirectory = new ExcelDirectory(level, f.getName(),
							f.getAbsolutePath(), getSubPath(rootPath, f.getAbsolutePath()), rootPath);

					directory.getChildDirectorys().add(childDirectory);

					String relPath = childDirectory.getRelatPath();
					if (childDirectory.getRelatPath().contains(pName)) {
						relPath = childDirectory.getRelatPath().replaceAll(pName, cName);
						direCount++;
						FileUtils.makeDirs(newRootPath + relPath);
					} else {
						FileUtils.makeDirs(newRootPath + relPath);
					}

					//加载 下一级别的文件夹内容
					loadFile(childDirectory, rootPath);

					//	System.out.println("Dir:" + f.getAbsoluteFile());
				} else if (f.isFile() && f.getName().contains("xls")) {

					// 加载对比文件
					ExcelFile excelFile = new ExcelFile(level, f.getName(), f.getAbsolutePath(), newRootPath + directory.getRelatPath());
					directory.getFileList().add(excelFile);
					//	System.out.println("File:" + f.getAbsoluteFile());
				}
			}
		} catch (Exception e) {

			megDetail.append("	修改错误，请检查科目名称，原因：" + e.getMessage() + "    \r\n \r\n");

//			FileUtils.deleteDirectory(newRootPath);

			throw e;

		}
	}

	private String getSubPath(String rootPath, String abPath) {
		return abPath.replace(rootPath, "");
	}

	/**
	 * 获得用户界面输入内容
	 *
	 * @return
	 */
	private String catchInput() throws IOException {

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

		String strIn = bufferedReader.readLine();

		File root = new File(strIn);

		if (root.isDirectory())
			return strIn;
		else {
			System.out.println("该路径不存在，请重新输入！");
			return catchInput();
		}
	}


	private boolean isExistDir(String str) {

		File root = new File(str);

		if (root.isDirectory())
			return true;
		else {
			return false;
		}
	}


}
